<?php

/**
 * ECSHOP 商品分类
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: category.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}




/* 初始化分页信息 */
$page = isset($_REQUEST['page'])   && intval($_REQUEST['page'])  > 0 ? intval($_REQUEST['page'])  : 1;
$size = isset($_CFG['page_size'])  && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10;
$brand = isset($_REQUEST['brand']) && intval($_REQUEST['brand']) > 0 ? intval($_REQUEST['brand']) : 0;
$origin = isset($_REQUEST['origin']) && !empty($_REQUEST['origin']) ? trim($_REQUEST['origin']) : '';
$price_max = isset($_REQUEST['price_max']) && intval($_REQUEST['price_max']) > 0 ? intval($_REQUEST['price_max']) : 0;
$price_min = isset($_REQUEST['price_min']) && intval($_REQUEST['price_min']) > 0 ? intval($_REQUEST['price_min']) : 0;
$filter_attr_str = isset($_REQUEST['filter_attr']) ? htmlspecialchars(trim($_REQUEST['filter_attr'])) : '0';

$filter_attr_str = trim(urldecode($filter_attr_str));
$filter_attr_str = preg_match('/^[\d\.]+$/',$filter_attr_str) ? $filter_attr_str : '';
$filter_attr = empty($filter_attr_str) ? '' : explode('.', $filter_attr_str);


/* 排序、显示方式以及类型 */
$default_display_type = $_CFG['show_order_type'] == '0' ? 'list' : ($_CFG['show_order_type'] == '1' ? 'grid' : 'text');
$default_sort_order_method = $_CFG['sort_order_method'] == '0' ? 'DESC' : 'ASC';
$default_sort_order_type   = $_CFG['sort_order_type'] == '0' ? 'goods_id' : ($_CFG['sort_order_type'] == '1' ? 'goods_id' : 'last_update');

$sort  = (isset($_REQUEST['sort'])  && in_array(trim(strtolower($_REQUEST['sort'])), array('goods_id', 'shop_price', 'last_update', 'click_count', 'sales_volume','is_advance'))) ? trim($_REQUEST['sort'])  : $default_sort_order_type;
$order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC')))                              ? trim($_REQUEST['order']) : $default_sort_order_method;


$display  = (isset($_REQUEST['display']) && in_array(trim(strtolower($_REQUEST['display'])), array('grid', 'list', 'text'))) ? trim($_REQUEST['display'])  : (isset($_COOKIE['ECS']['display']) ? $_COOKIE['ECS']['display'] : $default_display_type);
$display  = in_array($display, array('list', 'grid', 'text')) ? $display : 'text';
setcookie('ECS[display]', $display, gmtime() + 86400 * 7);

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'asynclist')
{
	include('includes/cls_json.php');
	$json   = new JSON;

	$last = isset($_REQUEST['last']) ? intval($_REQUEST['last']) : 0;
	$amount = isset($_REQUEST['amount']) ? intval($_REQUEST['amount']) : 10;

	$sql = "SELECT g.origin ".
			"FROM ".$GLOBALS['ecs']->table('goods')." AS g ".
			"WHERE g.origin!='' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
			"GROUP BY g.origin";
	$os = $GLOBALS['db']->getCol($sql);
	
	if (!empty($origin) && !in_array($origin, $os))
	{
		ecs_header("Location: ./\n");
	
		exit;
	}
    

	
	$sql = "SELECT c.filter_attr FROM ".$ecs->table('category')." AS c ,".$ecs->table('attribute')." AS a ".
			" WHERE c.is_show=1 AND c.filter_attr IS NOT NULL AND c.filter_attr!='' GROUP BY a.attr_name";
	$res = $db->getCol($sql);
	$res = array_unique($res);
	$country_attr_list = implode(',', $res);

	/* 赋值固定内容 */
	if ($brand > 0)
	{
		$sql = "SELECT brand_name FROM " .$GLOBALS['ecs']->table('brand'). " WHERE brand_id = '$brand'";
		$brand_name = $db->getOne($sql);
	}
	else
	{
		$brand_name = '';
	}

	
	/* 品牌筛选 */

    $sql = "SELECT b.brand_id, b.brand_name, COUNT(*) AS goods_num ".
            "FROM " . $GLOBALS['ecs']->table('brand') . "AS b, ".
                $GLOBALS['ecs']->table('goods') . " AS g ".
            "WHERE g.brand_id = b.brand_id AND b.is_show = 1 " .
            " AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
            "GROUP BY b.brand_id HAVING goods_num > 0 ORDER BY b.sort_order, b.brand_id ASC";

    $brands = $GLOBALS['db']->getAll($sql);
	
    foreach ($brands AS $key => $val)
    {
        $temp_key = $key + 1;
        $brands[$temp_key]['brand_name'] = $val['brand_name'];
        $brands[$temp_key]['url'] = build_uri('country', array('origin' => $origin, 'bid' => $val['brand_id'], 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str));
        $brands[$temp_key]['brand_id'] = $val['brand_id'];
        /* 判断品牌是否被选中 */
        if ($brand == $brands[$key]['brand_id'])
        {
            $brands[$temp_key]['selected'] = 1;
        }
        else
        {
            $brands[$temp_key]['selected'] = 0;
        }
    }
    $brands[0]['brand_id'] = 0;
    $brands[0]['brand_name'] = $_LANG['all_attribute'];
    $brands[0]['url'] = build_uri('country', array('origin' => $origin, 'bid' => 0, 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str));
    $brands[0]['selected'] = empty($brand) ? 1 : 0;

    
    /* 0216原产地筛选 */
    $sql = "SELECT g.origin, COUNT(*) AS goods_num ".
    		"FROM ".$GLOBALS['ecs']->table('goods')." AS g ".
    		"WHERE g.origin!='' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
    		"GROUP BY g.origin HAVING goods_num > 0 ";
    
    $origins = $GLOBALS['db']->getAll($sql);
    //     print_r($origins);
    // 	echo $origin;
    foreach ($origins AS $key => $val)
    {
    	$temp_key = $key + 1;
    	$origins[$temp_key]['url'] = build_uri('country', array('bid' => $brand, 'origin'=>$val['origin'] ,'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str));
    	$origins[$temp_key]['origin'] = $val['origin'];
    	$origins[$temp_key]['origin_id'] = $val['origin'];
    	/* 是否被选中 */
    	if ($origin == $origins[$temp_key]['origin'])
    	{
    		$origins[$temp_key]['selected'] = 1;
    	}
    	else
    	{
    		$origins[$temp_key]['selected'] = 0;
    	}
    }
    $origins[0]['origin_id'] = '';
    $origins[0]['origin'] = $_LANG['all_attribute'];
    $origins[0]['url'] = build_uri('country', array('bid' => $brand,'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str));
    $origins[0]['selected'] = empty($origin) ? 1 : 0;
    //     print_r($origins);
    
    /* 属性筛选 */
    $ext = ''; //商品查询条件扩展
    if (!empty($country_attr_list))
    {
        $country_filter_attr = explode(',', $country_attr_list);       //提取出此分类的筛选属性
        $all_attr_list = array();

        foreach ($country_filter_attr AS $key => $value)
        {
            $sql = "SELECT a.attr_name FROM " . $ecs->table('attribute') . " AS a, " . $ecs->table('goods_attr') . " AS ga, " . $ecs->table('goods') . " AS g WHERE a.attr_id = ga.attr_id AND g.goods_id = ga.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND a.attr_id='$value'";
            if($temp_name = $db->getOne($sql))
            {
                $all_attr_list[$key]['filter_attr_name'] = $temp_name;

                $sql = "SELECT a.attr_id, MIN(a.goods_attr_id ) AS goods_id, a.attr_value AS attr_value FROM " . $ecs->table('goods_attr') . " AS a, " . $ecs->table('goods') .
                       " AS g" .
                       " WHERE g.goods_id = a.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 ".
                       " AND a.attr_id='$value' ".
                       " GROUP BY a.attr_value";

                $attr_list = $db->getAll($sql);
				
                $temp_arrt_url_arr = array();

                for ($i = 0; $i < count($country_filter_attr); $i++)        //获取当前url中已选择属性的值，并保留在数组中
                {
                    $temp_arrt_url_arr[$i] = !empty($filter_attr[$i]) ? $filter_attr[$i] : 0;
                }

                $temp_arrt_url_arr[$key] = 0;                           //“全部”的信息生成
                $temp_arrt_url = implode('.', $temp_arrt_url_arr);
                $all_attr_list[$key]['attr_list'][0]['attr_value'] = $_LANG['all_attribute'];
                $all_attr_list[$key]['attr_list'][0]['url'] = build_uri('country', array('bid'=>$brand, 'origin'=>$origin, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url));
                $all_attr_list[$key]['attr_list'][0]['selected'] = empty($filter_attr[$key]) ? 1 : 0;
                $all_attr_list[$key]['attr_list'][0]['goods_attr_id']  = 0;

                foreach ($attr_list as $k => $v)
                {
                    $temp_key = $k + 1;
                    $temp_arrt_url_arr[$key] = $v['goods_id'];       //为url中代表当前筛选属性的位置变量赋值,并生成以‘.’分隔的筛选属性字符串
                    $temp_arrt_url = implode('.', $temp_arrt_url_arr);

                    $all_attr_list[$key]['attr_list'][$temp_key]['attr_value'] = $v['attr_value'];
                    $all_attr_list[$key]['attr_list'][$temp_key]['url'] = build_uri('country', array('bid'=>$brand, 'origin'=>$origin, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url));
                    $all_attr_list[$key]['attr_list'][$temp_key]['goods_attr_id'] = $v['goods_id'];
                    if (!empty($filter_attr[$key]) AND $filter_attr[$key] == $v['goods_id'])
                    {
                        $all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 1;
                    }
                    else
                    {
                        $all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 0;
                    }
                }
            }

        }
// 		print_r($all_attr_list);
        /* 扩展商品查询条件 */
         if (!empty($filter_attr))
         {
             $ext_sql = "SELECT DISTINCT(b.goods_id) FROM " . $ecs->table('goods_attr') . " AS a, " . $ecs->table('goods_attr') . " AS b " .  "WHERE ";
             $ext_group_goods = array();
           

             foreach ($filter_attr AS $k => $v)                      // 查出符合所有筛选属性条件的商品id */
             {
                 if (is_numeric($v) && $v !=0 &&isset($country_filter_attr[$k]))
                 {
                 	$sql = $ext_sql . "b.attr_value = a.attr_value AND b.attr_id = " . $country_filter_attr[$k] ." AND a.goods_attr_id = " . $v;
//                  	 $attr_value = $db->getOne("SELECT attr_value FROM ".$ecs->table('goods_attr')." WHERE goods_attr_id='$v' "); 
//                      $sql = $ext_sql . "b.attr_value = a.attr_value AND a.attr_value ='$attr_value' " ;
                     $ext_group_goods = $db->getColCached($sql);
                     $ext .= ' AND ' . db_create_in($ext_group_goods, 'g.goods_id');
                 }
             }
         }
     }

	$goods_list = country_get_goods2($children, $brand, $origin, $price_min, $price_max, $ext, $amount, $last, $sort, $order);
	foreach($goods_list as $key=>$var)
	{
		$sayList[] = array(
				'pro-inner'=>'<div class="proImg-wrap"><a href="'.$var['url'].'"><img alt="'.$var['name'].'" src="'.$var['goods_img'].'"></a></div><div class="proInfo-wrap"><div class="proTitle"><a href="'.$var['url'].'">'.$var['name'].'</a></div><div class="proSKU"></div><div class="proPrice"><em>'.$var['price_str'].'</em></div><div class="proService"><del>'.$var['market_price'].'</del></div><div class="proSales">销量:<em>'.$var['sales_count'].'</em></div><div class="proIcons">'.$var['watermark_str'].'</div></div>'
		);
	}

	die($json->encode($sayList));
}
/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */

/* 页面的缓存ID */
$cache_id = sprintf('%X', crc32($display . '-' . $sort  .'-' . $order  .'-' . $page . '-' . $size . '-' . $_SESSION['user_rank'] . '-' .
    $_CFG['lang'] .'-'. $brand .'-'. $origin. '-' . $price_max . '-' .$price_min . '-' . $filter_attr_str));


$dwt_name = 'category';


if (!$smarty->is_cached($dwt_name.'.dwt', $cache_id))
{
    /* 如果页面没有被缓存则重新获取页面的内容 */
	
	$sql = "SELECT g.origin ".
			"FROM ".$GLOBALS['ecs']->table('goods')." AS g ".
			"WHERE g.origin!='' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
			"GROUP BY g.origin";
	$os = $GLOBALS['db']->getCol($sql);
	
	if (!empty($origin) && !in_array($origin, $os))
	{
		ecs_header("Location: ./\n");
	
		exit;
	}
    

	
	$sql = "SELECT c.filter_attr FROM ".$ecs->table('category')." AS c ,".$ecs->table('attribute')." AS a ".
			" WHERE c.is_show=1 AND c.filter_attr IS NOT NULL AND c.filter_attr!='' GROUP BY a.attr_name";
	$res = $db->getCol($sql);
	$res = array_unique($res);
	$country_attr_list = implode(',', $res);

	

    /* 品牌筛选 */

    $sql = "SELECT b.brand_id, b.brand_name, COUNT(*) AS goods_num ".
            "FROM " . $GLOBALS['ecs']->table('brand') . "AS b, ".
                $GLOBALS['ecs']->table('goods') . " AS g ".
            "WHERE g.brand_id = b.brand_id AND b.is_show = 1 " .
            " AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
            "GROUP BY b.brand_id HAVING goods_num > 0 ORDER BY b.sort_order, b.brand_id ASC";

    $brands = $GLOBALS['db']->getAll($sql);
	
    foreach ($brands AS $key => $val)
    {
        $temp_key = $key + 1;
        $brands[$temp_key]['brand_name'] = $val['brand_name'];
        $brands[$temp_key]['url'] = build_uri('country', array('origin' => $origin, 'bid' => $val['brand_id'], 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str));
        $brands[$temp_key]['brand_id'] = $val['brand_id'];
        /* 判断品牌是否被选中 */
        if ($brand == $brands[$key]['brand_id'])
        {
            $brands[$temp_key]['selected'] = 1;
        }
        else
        {
            $brands[$temp_key]['selected'] = 0;
        }
    }
    $brands[0]['brand_id'] = 0;
    $brands[0]['brand_name'] = $_LANG['all_attribute'];
    $brands[0]['url'] = build_uri('country', array('origin' => $origin, 'bid' => 0, 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str));
    $brands[0]['selected'] = empty($brand) ? 1 : 0;

    $smarty->assign('brands', $brands);

    
    /* 0216原产地筛选 */
    $sql = "SELECT g.origin, COUNT(*) AS goods_num ".
    		"FROM ".$GLOBALS['ecs']->table('goods')." AS g ".
    		"WHERE g.origin!='' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
    		"GROUP BY g.origin HAVING goods_num > 0 ";
    
    $origins = $GLOBALS['db']->getAll($sql);
    //     print_r($origins);
    // 	echo $origin;
    foreach ($origins AS $key => $val)
    {
    	$temp_key = $key + 1;
    	$origins[$temp_key]['url'] = build_uri('country', array('bid' => $brand, 'origin'=>$val['origin'] ,'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str));
    	$origins[$temp_key]['origin'] = $val['origin'];
    	$origins[$temp_key]['origin_id'] = $val['origin'];
    	/* 是否被选中 */
    	if ($origin == $origins[$temp_key]['origin'])
    	{
    		$origins[$temp_key]['selected'] = 1;
    	}
    	else
    	{
    		$origins[$temp_key]['selected'] = 0;
    	}
    }
    $origins[0]['origin_id'] = '';
    $origins[0]['origin'] = $_LANG['all_attribute'];
    $origins[0]['url'] = build_uri('country', array('bid' => $brand,'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str));
    $origins[0]['selected'] = empty($origin) ? 1 : 0;
    //     print_r($origins);
    $smarty->assign('origins', $origins);
    
    /* 属性筛选 */
    $ext = ''; //商品查询条件扩展
    if (!empty($country_attr_list))
    {
        $country_filter_attr = explode(',', $country_attr_list);       //提取出此分类的筛选属性
        $all_attr_list = array();

        foreach ($country_filter_attr AS $key => $value)
        {
            $sql = "SELECT a.attr_name FROM " . $ecs->table('attribute') . " AS a, " . $ecs->table('goods_attr') . " AS ga, " . $ecs->table('goods') . " AS g WHERE a.attr_id = ga.attr_id AND g.goods_id = ga.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND a.attr_id='$value'";
            if($temp_name = $db->getOne($sql))
            {
                $all_attr_list[$key]['filter_attr_name'] = $temp_name;

                $sql = "SELECT a.attr_id, MIN(a.goods_attr_id ) AS goods_id, a.attr_value AS attr_value FROM " . $ecs->table('goods_attr') . " AS a, " . $ecs->table('goods') .
                       " AS g" .
                       " WHERE g.goods_id = a.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 ".
                       " AND a.attr_id='$value' ".
                       " GROUP BY a.attr_value";

                $attr_list = $db->getAll($sql);
				
                $temp_arrt_url_arr = array();

                for ($i = 0; $i < count($country_filter_attr); $i++)        //获取当前url中已选择属性的值，并保留在数组中
                {
                    $temp_arrt_url_arr[$i] = !empty($filter_attr[$i]) ? $filter_attr[$i] : 0;
                }

                $temp_arrt_url_arr[$key] = 0;                           //“全部”的信息生成
                $temp_arrt_url = implode('.', $temp_arrt_url_arr);
                $all_attr_list[$key]['attr_list'][0]['attr_value'] = $_LANG['all_attribute'];
                $all_attr_list[$key]['attr_list'][0]['url'] = build_uri('country', array('bid'=>$brand, 'origin'=>$origin, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url));
                $all_attr_list[$key]['attr_list'][0]['selected'] = empty($filter_attr[$key]) ? 1 : 0;
                $all_attr_list[$key]['attr_list'][0]['goods_attr_id']  = 0;

                foreach ($attr_list as $k => $v)
                {
                    $temp_key = $k + 1;
                    $temp_arrt_url_arr[$key] = $v['goods_id'];       //为url中代表当前筛选属性的位置变量赋值,并生成以‘.’分隔的筛选属性字符串
                    $temp_arrt_url = implode('.', $temp_arrt_url_arr);

                    $all_attr_list[$key]['attr_list'][$temp_key]['attr_value'] = $v['attr_value'];
                    $all_attr_list[$key]['attr_list'][$temp_key]['url'] = build_uri('country', array('bid'=>$brand, 'origin'=>$origin, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url));
                    $all_attr_list[$key]['attr_list'][$temp_key]['goods_attr_id'] = $v['goods_id'];
                    if (!empty($filter_attr[$key]) AND $filter_attr[$key] == $v['goods_id'])
                    {
                        $all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 1;
                    }
                    else
                    {
                        $all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 0;
                    }
                }
            }

        }
// 		print_r($all_attr_list);
        $smarty->assign('filter_attr_list',  $all_attr_list);
	
        /* 扩展商品查询条件 */
         if (!empty($filter_attr))
         {
             $ext_sql = "SELECT DISTINCT(b.goods_id) FROM " . $ecs->table('goods_attr') . " AS a, " . $ecs->table('goods_attr') . " AS b " .  "WHERE ";
             $ext_group_goods = array();
           

             foreach ($filter_attr AS $k => $v)                      // 查出符合所有筛选属性条件的商品id */
             {
                 if (is_numeric($v) && $v !=0 &&isset($country_filter_attr[$k]))
                 {
                 	$sql = $ext_sql . "b.attr_value = a.attr_value AND b.attr_id = " . $country_filter_attr[$k] ." AND a.goods_attr_id = " . $v;
//                  	 $attr_value = $db->getOne("SELECT attr_value FROM ".$ecs->table('goods_attr')." WHERE goods_attr_id='$v' "); 
//                      $sql = $ext_sql . "b.attr_value = a.attr_value AND a.attr_value ='$attr_value' " ;
                     $ext_group_goods = $db->getColCached($sql);
                     $ext .= ' AND ' . db_create_in($ext_group_goods, 'g.goods_id');
                 }
             }
         }
     }
// 	echo $ext;
    assign_template('c');


    $page_title = $GLOBALS['_CFG']['shop_title'];
    $ur_here    = '<a href=".">' . $GLOBALS['_LANG']['home'] . '</a>' . ' <code>></code> 所有商品';
    
    $smarty->assign('page_title',       $page_title);    // 页面标题
    $smarty->assign('ur_here',          $ur_here);  // 当前位置

    $smarty->assign('keywords',   '');
    $smarty->assign('description', '');

	
	
    $smarty->assign('cfg', $_CFG);
	
    $smarty->assign('show_marketprice', $_CFG['show_marketprice']);
	
    $smarty->assign('origin',$origin);
    $smarty->assign('brand_id',         $brand);
    $smarty->assign('price_max',        $price_max);
    $smarty->assign('price_min',        $price_min);
    $smarty->assign('filter_attr',      $filter_attr_str);
    $smarty->assign('feed_url',         ($_CFG['rewrite'] == 1) ? "feed-c$cat_id.xml" : 'feed.php?cat=' . $cat_id); // RSS URL
	
	
	//顶级分类页据输出部分
// 	if($cat['parent_id'] == 0)
// 	{
// 		$smarty->assign('categories_child',      get_cat_child($cat_id));
// 		$smarty->assign('categories_child_goods',      get_cat_child_goods($cat_id));
// 		$smarty->assign('like_goods',      like_goods($cat_id));
// 		$smarty->assign('browse_related',      browse_related());
// 	}
// 	else
// 	{
// 		$smarty->assign('sales_volume',    sales_volume($cat_id));
// 		$smarty->assign('categories_left',  get_categories_tree_left($cat_id)); 
// 		$smarty->assign('on_cat_name',  get_on_cat_name($cat_id));	
// 		$smarty->assign('crumb_list',  crumb_list($cat_id));
// 		$smarty->assign('browse_related',      browse_related());
// 		$smarty->assign('get_categories_tree_left_all',  get_categories_tree_left_all($cat_id)); 	

// 	}

    $smarty->assign('data_dir',    DATA_DIR);

    $smarty->assign('promotion_info', get_promotion_info());


    /* 调查 */
    $vote = get_vote();
    if (!empty($vote))
    {
        $smarty->assign('vote_id',     $vote['id']);
        $smarty->assign('vote',        $vote['content']);
    }


    $count = get_country_goods_count($brand, $origin, $price_min, $price_max, $ext);
    $max_page = ($count> 0) ? ceil($count / $size) : 1;
    if ($page > $max_page)
    {
        $page = $max_page;
    }
    $goodslist = country_get_goods($brand, $origin, $price_min, $price_max, $ext, $size, $page, $sort, $order);
	
    if($display == 'grid')
    {
        if(count($goodslist) % 2 != 0)
        {
            $goodslist[] = array();
        }
    }
	
    $smarty->assign('goods_list',       $goodslist);
    $smarty->assign('rewrite_list','country');
    $smarty->assign('script_name', 'country');
	$smarty->assign('category',0);
    assign_pager('country',  '',$count, $size, $sort, $order, $page, '', $brand, $price_min, $price_max, $display, $filter_attr_str, $origin); // 分页
    $smarty->assign('total_goods',sprintf($_LANG['total_goods'],$count));
    
    assign_dynamic($dwt_name); // 动态内容
}

$smarty->display($dwt_name.'.dwt', $cache_id);

/*------------------------------------------------------ */
//-- PRIVATE FUNCTION
/*------------------------------------------------------ */


/**
 * 
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function country_get_goods($brand, $origin, $min, $max, $ext, $size, $page, $sort, $order)
{
    $display = $GLOBALS['display'];
    $where = "g.is_on_sale = 1 AND g.is_alone_sale = 1 AND ".
            "g.is_delete = 0 ";

    if ($brand > 0)
    {
        $where .=  "AND g.brand_id=$brand ";
    }

    if (!empty($origin))
    {
    	$where .=  "AND g.origin='$origin' ";
    }
    
    if ($min > 0)
    {
        $where .= " AND g.shop_price >= $min ";
    }

    if ($max > 0)
    {
        $where .= " AND g.shop_price <= $max ";
    }

     /* 获得商品列表 */
    $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, ' .
                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, g.goods_type, " .
                'g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img, g.collection_id, g.sales_volume, g.goods_number ' .
            'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . ' AS mp ' .
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " .
            "WHERE $where $ext ORDER BY $sort $order";
    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['promote_price'] > 0)
        {
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }
        else
        {
            $promote_price = 0;
        }

        /* 处理商品水印图片 */
        $watermark_img = '';

        if ($promote_price != 0)
        {
            $watermark_img = "watermark_promote_small";
        }
        elseif ($row['is_new'] != 0)
        {
            $watermark_img = "watermark_new_small";
        }
        elseif ($row['is_best'] != 0)
        {
            $watermark_img = "watermark_best_small";
        }
        elseif ($row['is_hot'] != 0)
        {
            $watermark_img = 'watermark_hot_small';
        }

        if ($watermark_img != '')
        {
            $arr[$row['goods_id']]['watermark_img'] =  $watermark_img;
        }

        $arr[$row['goods_id']]['goods_id']         = $row['goods_id'];
        if($display == 'grid')
        {
            $arr[$row['goods_id']]['goods_name']       = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        }
        else
        {
            $arr[$row['goods_id']]['goods_name']       = $row['goods_name'];
        }
		
		$properties = get_goods_properties($row['goods_id']);  // 获得商品的规格和属性

		$arr[$row['goods_id']]['properties_pro'] = $properties['pro']['商品属性'];

		$arr[$row['goods_id']]['brief'] = $row['goods_brief'];
		
		$arr[$row['goods_id']]['is_new']  =  $row['is_new']  ? $row['is_new']  : 0 ;
		$arr[$row['goods_id']]['is_best'] =  $row['is_best'] ? $row['is_best'] : 0 ;
		$arr[$row['goods_id']]['is_hot']  =  $row['is_hot']  ? $row['is_hot']  : 0 ;
        $arr[$row['goods_id']]['name']             = $row['goods_name'];
		
		$goods_id = $row['goods_id'];
        $arr[$row['goods_id']]['goods_brief']      = $row['goods_brief'];
        $arr[$row['goods_id']]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']);
        $arr[$row['goods_id']]['market_price']     = $row['market_price'];
        $arr[$row['goods_id']]['shop_price']       = $row['shop_price'];
        $arr[$row['goods_id']]['type']             = $row['goods_type'];
        $arr[$row['goods_id']]['promote_price']    = ($promote_price > 0) ? $promote_price : '';
        $arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']));
        $arr[$row['goods_id']]['sales_volume']	   = sprintf($GLOBALS['_LANG']['had_bought'],$row['sales_volume']);
        $arr[$row['goods_id']]['goods_number']     = $row['goods_number'];
    }


    return $arr;
}

/**
 * 
 *
 * @access  public
 * @param   string     $cat_id
 * @return  integer
 */
function get_country_goods_count($brand = 0,$origin = '', $min = 0, $max = 0, $ext='')
{
    $where  = "g.is_on_sale = 1 AND (g.is_alone_sale = 1 OR g.is_promote = 1 OR g.is_advance = 1) AND g.is_delete = 0 " ;

    if ($brand > 0)
    {
        $where .=  " AND g.brand_id = $brand ";
    }
    
    if (!empty($origin))
    {
    	$where .=  " AND g.origin = '$origin' ";
    }

    if ($min > 0)
    {
        $where .= " AND g.shop_price >= $min ";
    }

    if ($max > 0)
    {
        $where .= " AND g.shop_price <= $max ";
    }

    /* 返回商品总数 */
    return $GLOBALS['db']->getOne('SELECT COUNT(DISTINCT g.goods_name) FROM ' . $GLOBALS['ecs']->table('goods') . " AS g WHERE $where $ext");
}

/**
 * ajax获取商品列表
 * @param unknown $children
 * @param unknown $brand
 * @param unknown $origin
 * @param unknown $min
 * @param unknown $max
 * @param unknown $ext
 * @param unknown $size
 * @param unknown $last
 * @param unknown $sort
 * @param unknown $order
 */
function country_get_goods2($children, $brand, $origin, $min, $max, $ext, $size, $last, $sort, $order)
{
	$display = $GLOBALS['display'];
    $where = "g.is_on_sale = 1 AND (g.is_alone_sale = 1 OR g.is_promote = 1 OR g.is_advance = 1) AND ".
            "g.is_delete = 0 ";

    if ($brand > 0)
    {
        $where .=  "AND g.brand_id=$brand ";
    }

    if (!empty($origin))
    {
    	$where .=  "AND g.origin='$origin' ";
    }
    
    if ($min > 0)
    {
        $where .= " AND g.shop_price >= $min ";
    }

    if ($max > 0)
    {
        $where .= " AND g.shop_price <= $max ";
    }

     /* 获得商品列表 */
    $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, ' .
                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, g.goods_type, g.is_advance, " .
                'g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img, g.collection_id, g.sales_volume, g.goods_number,g.click_count ' .
            'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . ' AS mp ' .
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " .
            "WHERE $where $ext GROUP BY g.goods_name ORDER BY $sort $order";
	$res = $GLOBALS['db']->selectLimit($sql, $size, $last);
	$arr = array();
	while ($row = $GLOBALS['db']->fetchRow($res))
	{
		if ($row['promote_price'] > 0)
		{
			$promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
		}
		else
		{
			$promote_price = 0;
		}

		/* 处理商品水印图片 */
		$watermark_img = '';

		if ($row['is_advance'] != 0)
        {
        	$watermark_img = "watermark_advance_small";
        }
        elseif ($promote_price != 0)
		{
			$watermark_img = "watermark_promote_small";
		}
		elseif ($row['is_new'] != 0)
		{
			$watermark_img = "watermark_new_small";
		}
		elseif ($row['is_best'] != 0)
		{
			$watermark_img = "watermark_best_small";
		}
		elseif ($row['is_hot'] != 0)
		{
			$watermark_img = 'watermark_hot_small';
		}

		if ($watermark_img != '')
		{
			$arr[$row['goods_id']]['watermark_img'] =  $watermark_img;
		}

		$arr[$row['goods_id']]['goods_id']         = $row['goods_id'];
		if($display == 'grid')
		{
			$arr[$row['goods_id']]['goods_name']       = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
		}
		else
		{
			$arr[$row['goods_id']]['goods_name']       = $row['goods_name'];
		}
		$arr[$row['goods_id']]['name']             = $row['goods_name'];
		$arr[$row['goods_id']]['goods_brief']      = $row['goods_brief'];
		$arr[$row['goods_id']]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']);
		$arr[$row['goods_id']]['market_price']     = price_format($row['market_price']);
		$arr[$row['goods_id']]['shop_price']       = price_format($row['shop_price']);
		$arr[$row['goods_id']]['type']             = $row['goods_type'];
		$arr[$row['goods_id']]['promote_price']    = ($promote_price > 0) ? price_format($promote_price) : '';
		$arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
		$arr[$row['goods_id']]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
		$arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

// 		$arr[$row['goods_id']]['sales_count']      = get_goods_sales_count($row['goods_id']);
		$arr[$row['goods_id']]['sales_count']      = $row['sales_volume'];
		$arr[$row['goods_id']]['watermark_str']    =  ($watermark_img != '') ? '<img width="55" height="16" src="themes/blue/images/'.$watermark_img.'.png" alt="'.$row['goods_name'].'">' : '';;
		$arr[$row['goods_id']]['price_str']    =  ($promote_price > 0) ? price_format($promote_price) : price_format($row['shop_price']);
		
		$arr[$row['goods_id']]['sales_volume']	   = sprintf($GLOBALS['_LANG']['had_bought'],$row['sales_volume']);
		$arr[$row['goods_id']]['goods_number']     = $row['goods_number'];
	}

	return $arr;
}


?>
